<!-- 功能管理页面 -->
<script setup lang="ts">
import {computed, ref, onBeforeMount} from 'vue'
import {HeaderData, Operation as Opr} from '@/components/dTable/dTable'
import {ElMessage} from 'element-plus'
import dTable from '@/components/dTable/dTable.vue'
import operation from '@/components//dTable/components/operation.vue'
import dDialog from '@/components/dDialog/dDialog.vue'
import {addDictItem, addDictItemDatas, getDictItem} from '@/api/baseSetting/dictionaryManager'
import userCommon from '@/store/common'
import {ColorRed, ColorTheme} from '@/api/config'
const common = userCommon.setup().store
const emits = defineEmits(['cancel', 'confirm', 'close'])
const props = defineProps({
  //显示
  showDialog: {
    type: Boolean,
    required: true
  },
  popId: {
    type: String,
    required: true
  },
  dictCode: {
    type: String,
    required: true
  }
})

// 操作按钮数据
const operationDataDelete: Array<Opr> = [{code: 'delete', label: '删除', iconConfig: {icon: 'common-delete', type: 'custom', color: ColorRed, size: 20}}]

// 操作按钮数据
const operationDataAdd: Array<Opr> = [{code: 'add', label: '添加', iconConfig: {icon: 'common-swap-add', type: 'custom', color: ColorTheme, size: 20}}]

const Id = computed(() => {
  return props.popId
})

const dictCode = computed(() => {
  return props.dictCode
})

const baseAdd = {
  dictItemName: '',
  englishName: '',
  dictItemCode: null,
  sort: null,
  operation: [],
  dictId: '',
  dictCode: dictCode.value
}
//添加展示按钮
const showButton = (dataList:Array<addDictItemDatas>) => {
  const returnList:Array<addDictItemDatas> = []
  if (!dataList.length) {
    const newAdd = JSON.parse(JSON.stringify(baseAdd))
    newAdd.dictItemCode = 1
    dataList.push(newAdd)
  }
  dataList.map((item, index) => {
    returnList.push({...item, operation:index === (dataList.length - 1) ? [...operationDataAdd, ...operationDataDelete] : operationDataDelete})
  })
  return returnList
}

const tableData = ref<Array<addDictItemDatas>>([])
// 查询子项
const IfdictItem = () => {
  getDictItem({id: Id.value}).then((res) => {
    const {data} = res.data as any
    tableData.value = showButton(data.childs)
  })
}
// 修改接口
const IfaddDictItem = () => {
  const dictLsit = tableData.value.map((item) => {
    return {
      id: item.id,
      name: item.name,
      sort: item.sort
    }
  })
  if (dictLsit.length === 1 && dictLsit[0].name === '') {
    dictLsit.length = 0
  }
  const params = {
    id: props.popId,
    childs: dictLsit
  }
  addDictItem(params).then((res) => {
    ElMessage({
      type: 'success',
      message: '操作成功'
    })
    emits('confirm', Id.value)
    // common.setDicData(dictCode.value, dictLsit)

  })
}

// 删除接口
const IfremoveItem = (_id: string, index: number) => {
  tableData.value.splice(index, 1)
  tableData.value = showButton(tableData.value)
}

// 弹窗取消
const oncancel = () => {
  emits('cancel', Id.value)
}
// 弹窗关闭
const onClose = () => {
  emits('close', Id.value)
}
// 弹窗保存
const onConfirm = () => {
  tableData.value.map((item) => {
    if (item.name.length > 50) {
      ElMessage.error(
        '字典项请输入汉字、字母、数字、字符,并且长度小于50字符'
      )
      throw Error()
    }
    if (
      tableData.value.length > 1 && (item.name === '' || item.sort === null)
    ) {
      ElMessage.error(
        '请检查字典项或者字典排序是否填写完整'
      )
      throw Error()
    }
    if (
      tableData.value.length === 1 && item.name === '' && item.sort !== null
    ) {
      ElMessage.error(
        '请检查字典项是否填写完整'
      )
      throw Error()
    }
    if (
      tableData.value.length === 1 && item.name !== '' && item.sort === null
    ) {
      ElMessage.error(
        '请检查字典排序是否填写完整'
      )
      throw Error()
    }
  })
  IfaddDictItem()
}
// 获取最大的值
const getMaxCode = () => {
  const list :Array<number> = []
  tableData.value.map((item) => {
    list.push(parseInt(item.id + ''))
  })
  list.sort((a, b) => {
    return b - a
  })
  return list[0]
}

// 添加事件
const onAdd = () => {
  const addData = JSON.parse(JSON.stringify(baseAdd))
  addData.dictItemCode = getMaxCode() + 1
  tableData.value.push(addData)
  tableData.value = showButton(tableData.value)
}

// 操作栏点击
const onErtion = (code, row) => {
  if (code === 'delete') {
    IfremoveItem(row.id, tableData.value.indexOf(row))
  } else if (code === 'add') {
    onAdd()
  }
}

//表格数据
const tableHeaderDatas = ref<Array<HeaderData>>([
  {prop: 'name', label: '类型子项名称', columnType: 'input', align: 'center', 'min-width': '100'},
  {prop: 'id', label: '值', columnType: 'inputNumber', step: 1, min: 1, align: 'center', 'min-width': '100'},
  {prop: 'sort', label: '字典排序', columnType: 'inputNumber', step: 1, min: 1, align: 'center', 'min-width': '100'},
  {prop: 'operation', label: '操作', columnType: 'slot', 'width': '83'}
])
onBeforeMount(() => {
  IfdictItem()
})
</script>

<template>
  <d-dialog
    :title="'维护字典项'"
    :show-dialog="showDialog"
    @cancel="oncancel"
    @close="onClose"
    @confirm="onConfirm"
  >
    <d-table
      ref="main"
      class=".d-common-flex-full"
      style="min-height: 300px"
      :table-data="tableData"
      :table-header-data="tableHeaderDatas"
    >
      <template #operation="scope">
        <operation
          :row="scope.row"
          :col="scope.item"
          @opertion-click="onErtion"
        />
      </template>
    </d-table>
  </d-dialog>
</template>

<style scoped lang="less">
.btn {
  display: flex;
  justify-content: left;
  margin-bottom: 5px;
}
</style>
